import { useEffect, useRef, useState } from 'react'
import reactLogo from './assets/react.svg'
import { invoke } from '@tauri-apps/api/core'
import './App.css'
import { onOpenUrl } from '@tauri-apps/plugin-deep-link'
import { UnlistenFn, listen } from '@tauri-apps/api/event'

function App() {
  const [greetMsg, setGreetMsg] = useState('')
  const [name, setName] = useState('')
  const [args, setArgs] = useState(['11'])
  const [args2, setArgs2] = useState('22')
  const unLinkLis = useRef<UnlistenFn>()

  listen<string>('url', (event) => {
    setArgs2(event.payload)
  })
  async function greet() {
    // Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
    setGreetMsg(await invoke('greet', { name }))
  }

  useEffect(() => {
    onOpenUrl((urls) => {
      console.log('deep link:', urls)
      setArgs(urls)
    }).then((f) => (unLinkLis.current = f))

    return () => {
      unLinkLis.current?.()
    }
  })

  return (
    <div className="container">
      <h1>
        {args2}--Welcome to Tauri!{args}
      </h1>

      <div className="row">
        <a href="https://vitejs.dev" target="_blank">
          <img src="/vite.svg" className="logo vite" alt="Vite logo" />
        </a>
        <a href="https://tauri.app" target="_blank">
          <img src="/tauri.svg" className="logo tauri" alt="Tauri logo" />
        </a>
        <a href="https://reactjs.org" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>

      <p>Click on the Tauri, Vite, and React logos to learn more.</p>

      <form
        className="row"
        onSubmit={(e) => {
          e.preventDefault()
          greet()
        }}
      >
        <input id="greet-input" onChange={(e) => setName(e.currentTarget.value)} placeholder="Enter a name..." />
        <button type="submit">Greet</button>
      </form>

      <p>{greetMsg}</p>
    </div>
  )
}

export default App
